package org.example.xx2.controller;

import org.example.xx2.dto.*;
import org.example.xx2.model.User;
import org.example.xx2.service.UserService;
import org.example.xx2.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        return userService.login(request);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<String> register(@Valid @RequestBody RegisterRequest request) {
        return userService.register(request);
    }

    /**
     * 获取安全问题
     */
    @GetMapping("/forgot-password/question")
    public ApiResponse<String> getSecurityQuestion(@RequestParam String account) {
        return userService.getSecurityQuestion(account);
    }

    /**
     * 验证安全问题答案
     */
    @PostMapping("/forgot-password/verify")
    public ApiResponse<String> verifySecurityAnswer(@Valid @RequestBody ForgotPasswordRequest request) {
        return userService.verifySecurityAnswer(request);
    }

    /**
     * 发送手机验证码
     */
    @PostMapping("/forgot-password/phone-code")
    public ApiResponse<String> sendPhoneVerificationCode(@RequestBody ForgotPasswordRequest request) {
        return userService.sendPhoneVerificationCode(request.getPhone());
    }

    /**
     * 发送邮箱验证码
     */
    @PostMapping("/forgot-password/email-code")
    public ApiResponse<String> sendEmailVerificationCode(@RequestBody ForgotPasswordRequest request) {
        return userService.sendEmailVerificationCode(request.getEmail());
    }

    /**
     * 通过验证码重置密码
     */
    @PostMapping("/forgot-password/reset")
    public ApiResponse<String> resetPasswordByCode(@Valid @RequestBody ForgotPasswordRequest request) {
        return userService.resetPasswordByCode(request);
    }

    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public ApiResponse<String> changePassword(HttpServletRequest httpRequest, 
                                            @Valid @RequestBody ChangePasswordRequest request) {
        Integer userId = getUserIdFromToken(httpRequest);
        if (userId == null) {
            return ApiResponse.error(401, "未授权访问");
        }
        
        return userService.changePassword(userId, request);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public ApiResponse<User> getUserInfo(HttpServletRequest httpRequest) {
        Integer userId = getUserIdFromToken(httpRequest);
        if (userId == null) {
            return ApiResponse.error(401, "未授权访问");
        }
        
        return userService.getUserInfo(userId);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
//    public ApiResponse<String> updateUserInfo(HttpServletRequest httpRequest,
//                                            @Valid @RequestBody User user) {
//        Integer userId = getUserIdFromToken(httpRequest);
//        if (userId == null) {
//            return ApiResponse.error(401, "未授权访问");
//        }
//
//        return userService.updateUserInfo(userId, user);
//    }
    public ApiResponse<String> updateUserInfo(HttpServletRequest httpRequest,
                                              @Valid @RequestBody UpdateUserInfoRequest request) {
        Integer userId = getUserIdFromToken(httpRequest);
        if (userId == null) {
            return ApiResponse.error(401, "未授权访问");
        }

        // 将UpdateUserInfoRequest转换为User对象
        User user = new User();
        user.setName(request.getName());
        user.setAge(request.getAge());
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        user.setSex(request.getSex());
        user.setQuestion(request.getQuestion());
        user.setAsw(request.getAsw());

        return userService.updateUserInfo(userId, user);
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    public ApiResponse<Boolean> checkUsername(@RequestParam String account) {
        boolean exists = userService.isUsernameExists(account);
        return ApiResponse.success(!exists); // 返回true表示可用
    }

    /**
     * 检查手机号是否存在
     */
    @GetMapping("/check-phone")
    public ApiResponse<Boolean> checkPhone(@RequestParam String phone) {
        boolean exists = userService.isPhoneExists(phone);
        return ApiResponse.success(!exists); // 返回true表示可用
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check-email")
    public ApiResponse<Boolean> checkEmail(@RequestParam String email) {
        boolean exists = userService.isEmailExists(email);
        return ApiResponse.success(!exists); // 返回true表示可用
    }

    /**
     * 从JWT令牌中获取用户ID
     */
    private Integer getUserIdFromToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        String account = jwtUtil.getUsernameFromToken(token);
        if (account == null) {
            return null;
        }
        
        // 根据用户名获取用户信息
        User user = userService.findUserById(account);
        return user != null ? user.getId() : null;
    }
} 